package com.project.srtp.secure.util;

/**
 * @author 曹行阳
 * @version 0.1
 * @date 2025/6/10 16:52
 */

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 文件存储工具类：将加密后的文件写入本地磁盘目录
 */
public class FileStorageUtil {

    private static final String ROOT_DIR = System.getProperty("user.dir") + "/storage/secure/";

    static {
        File dir = new File(ROOT_DIR);
        if (!dir.exists()) dir.mkdirs();
    }

    public static File saveMultipartFile(MultipartFile multipartFile) throws IOException {
        String filename = generateTimestampedFileName(multipartFile.getOriginalFilename());
        Path target = Paths.get(ROOT_DIR + filename);
        Files.copy(multipartFile.getInputStream(), target);
        return target.toFile();
    }

    public static String writeEncryptedStream(InputStream encryptedInput, String keyFingerprint) throws IOException {
        String filename = generateTimestampedFileName(keyFingerprint + ".enc");
        Path target = Paths.get(ROOT_DIR + filename);
        try (OutputStream os = Files.newOutputStream(target)) {
            byte[] buffer = new byte[4096];
            int len;
            while ((len = encryptedInput.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
        }
        return target.toString();
    }

    public static File getEncryptedFile(String path) {
        return new File(path);
    }

    public static boolean deleteFile(String path) {
        File file = new File(path);
        return file.exists() && file.delete();
    }

    private static String generateTimestampedFileName(String baseName) {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        return timestamp + "_" + (baseName == null ? "file" : baseName);
    }
}
